﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using Indigox.SSO.Client;
using WebApplication.AppCode;
using BLL;
using Newtonsoft.Json;
using Model;

namespace WebApplication
{
    public partial class Login : System.Web.UI.Page
    {
        SysBLL bll = new SysBLL();

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
        {
            UserInfo user = null;
            if (ConfigurationManager.AppSettings["Debug"] == "true")
            {
                user = bll.DbContext.Users.FirstOrDefault(x => x.Account == this.Login1.UserName);
            }
            else if (ConfigurationManager.AppSettings["OpenSSO"].ToString().Equals("true"))
            {
                //生成校验对象，该对象由SSO开发包提供
                ValidateService validateService = new ValidateService(Context);
                //校验登录信息
                Assertion assertion = validateService.Validate();
                //获取登录用户名
                string userName = assertion.UserName;
                user = bll.DbContext.Users.FirstOrDefault(x => x.Account == userName);
            }
            else
            {
                //获取当前用户名和密码调用AD域用户验证
                ADHelper.InitArgs(ConfigurationManager.AppSettings["ADSyncString"]);
                if (ADHelper.LoginByAccount(this.Login1.UserName, this.Login1.Password) == ADHelper.LoginResult.LOGIN_USER_OK)
                {
                    user = bll.DbContext.Users.FirstOrDefault(x => x.Account == this.Login1.UserName);
                }
            }

            if (user == null)
            {
                e.Authenticated = false;
            }
            else
            {
                e.Authenticated = true;
                SaveLoginIdentify(user);
                Response.Redirect(Request["url"]);
            }
        }

        private void SaveLoginIdentify(UserInfo user)
        {
            var cookieString = JsonConvert.SerializeObject(user);
            HttpCookie cookie = new HttpCookie("UserInfo", HttpUtility.UrlEncode(Tools.Encrypt(cookieString).ToString()));
            cookie.Expires = DateTime.Now.AddMonths(1);
            Response.Cookies.Add(cookie);
            Session["UserInfo"] = user;
        }
    }
}